const axios = require('axios');
// const jsencrypt = require('jsencrypt');
const JSEncrypt = require('node-jsencrypt');
const CryptoJS = require('crypto-js');

const key = "1234567890123456"
const iv = "1111111111111110"

const jsonFormatter = {
  stringify: function(cipherParams) {
    var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }
    if (cipherParams.iv) {
      jsonObj.iv = cipherParams.iv.toString();
    }
    if (cipherParams.salt) {
      jsonObj.s = cipherParams.salt.toString();
    }
    return JSON.stringify(jsonObj);
  },

  parse: function(jsonStr) {
    var jsonObj = JSON.parse(jsonStr);
    var cipherParams = CryptoJS.lib.CipherParams.create({
      ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
    });
    if (jsonObj.iv) {
      cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
    }
    if (jsonObj.s) {
      cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
    }
    return cipherParams;
  }
};

function aesEncrypt(key, iv, plain){
    useKey = CryptoJS.enc.Utf8.parse(key)
    useIv = CryptoJS.enc.Utf8.parse(iv)

    cipherParam = CryptoJS.AES.encrypt(plain, useKey, 
        {iv:useIv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7, format:jsonFormatter}
        )

    const text=CryptoJS.enc.Base64.stringify(cipherParam.ciphertext)
    return text
}

function aesDecrypt(key, iv, cipher){
    useKey = CryptoJS.enc.Utf8.parse(key)
    useIv = CryptoJS.enc.Utf8.parse(iv)

    console.log("c", cipher)
    const parsed = CryptoJS.enc.Base64.parse(cipher)
    console.log("p", parsed)
    const decoded = CryptoJS.enc.Base64.stringify(parsed)
    console.log("d", decoded)
    const data = CryptoJS.AES.decrypt(parsed, useKey, {
      iv: useIv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7
    })
    console.log("d2", data)
    const text = data.toString(CryptoJS.enc.Utf8)
    console.log("t", text)
    return text;
}

fetch('http://localhost:8080/admin/config/system', {
  method:'GET',
  headers:{"Content-Type":"application/json;charset=utf-8"}
  }).then(resp=>resp.json())
  .then(json=>{
    publicKey=json.data.publicKey
    const jsEncrypt = new JSEncrypt();
    jsEncrypt.setPublicKey(publicKey);

    const encKey = jsEncrypt.encrypt(key);
    const encIv = jsEncrypt.encrypt(iv);

    const config = {
      headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'CRYPTO': encKey,
      'IV': encIv,
      'SIGN': '123',
    }};
    data = JSON.stringify({loginType:"email", email:"447341540@qq.com", password:"123456"})
    encData = aesEncrypt(key,iv,data)

    axios.post('http://localhost:8080/customer/login', encData, config)
    .then(response => {
        console.log(response.data);
        resp = aesDecrypt(response.data.data, key, iv)
        console.log("resp:",resp)
    })
    .catch(error => {
    }
  );
})